package com.dingreading.cloud.soms.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.CorpTeacherDto;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.soms.dto.CaScheduleDto;
import com.dingreading.cloud.soms.dto.CaTeacherDto;
import com.dingreading.cloud.soms.entity.*;
import com.dingreading.cloud.soms.service.*;
import com.dingreading.cloud.soms.util.ScheduleUtil;
import com.google.common.collect.Lists;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/caSchedule/v2")
@Api(tags = "门店-排课活动表管理V2")
public class FrontCaScheduleControllerV2 {

    @Resource
    protected StaffService staffService;
    @Resource
    protected CaClassService classService;
    @Resource
    protected CaTeacherService teacherService;
    @Resource
    protected CaClassroomsService classroomsService;
    @Resource
    protected CaScheduleService scheduleService;
    @Resource
    protected CaScheduleLessonService scheduleLessonService;
    @Resource
    protected StoresService storesService;
    @Resource
    protected MembersService membersService;
    @Resource
    protected StoreProjectsService storeProjectsService;
    @Resource
    protected CaCallNamesService callNameService;

    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "社团id") @RequestParam(value = "classId", required = false) Long classId,
            @ApiParam(value = "社团名称") @RequestParam(value = "className", required = false) String className,
            @ApiParam(value = "活动室id") @RequestParam(value = "roomId", required = false) Long roomId,
            @ApiParam(value = "教师username") @RequestParam(value = "username", required = false) String username,
            @ApiParam(value = "活动服务uid") @RequestParam(value = "projectUid", required = false) String projectUid,
            @ApiParam(value = "活动日期") @RequestParam(value = "teachDate", required = false) String teachDate,
            @ApiParam(value = "是否禁用 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        Page<CaScheduleDto> page = scheduleService.pageListV3(pageUtil, storeUid, null, enabled, classId, className, roomId, username, projectUid, teachDate);

        List<CaScheduleDto> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> uids = list.stream().map(CaScheduleDto::getScheduleUid).distinct().collect(Collectors.toList());
            List<CaTeacherDto> teacher = teacherService.getTeachersByScheduleUids(storeUid, uids, null);
            if (CollectionUtils.isNotEmpty(teacher)) {
                Map<String, List<CaTeacherDto>> map = teacher.stream().collect(Collectors.groupingBy(CaTeacherDto::getScheduleUid));
                for (CaScheduleDto schedule : list) {
                    schedule.setTeacherList(map.get(schedule.getScheduleUid()));
                }
            }
        }

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(list);
        return R.ok(data);
    }

    @ApiOperation(value = "获取课表详情")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "活动计划id") @RequestParam(value = "scheduleUid") String scheduleUid
    ) {
        CaScheduleDto data = scheduleService.getScheduleDto(storeUid, scheduleUid);
        if (data == null) return R.fail("活动计划获取失败");

        List<CaTeacherDto> teacherDtos = teacherService.getTeachers(storeUid, scheduleUid, null);
        data.setTeacherList(teacherDtos);
        return R.ok(data);
    }

    @ApiOperation(value = "删除课表及其活动")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "活动计划id") @RequestParam(value = "scheduleUid") String scheduleUid
    ) {
        // 删除前先判断，有没有排课逻辑
        CaSchedule data = scheduleService.getSchedule(storeUid, scheduleUid);
        if (data == null)
            return R.fail("活动计划获取失败");
        if (data.getUseLessonNum() > 0)
            return R.fail("活动计划的活动已开始，不能删除");

        long l = scheduleService.dropBean(storeUid, scheduleUid);
        if (l <= 0)
            return R.failDel();

        // 删除活动表下的活动
        scheduleLessonService.dropByScheduleUid(storeUid, scheduleUid);

        // 删除活动表下的主讲导读
        teacherService.dropTeacher(storeUid, scheduleUid);

        // 更新社团的排活动数
        if (data.getClassId() != null)
            classService.updateScheduleNum(corpUid, storeUid, data.getClassId(), -1);

        // 删除未开始点名的点名记录
        callNameService.dropByScheduleUid(storeUid, scheduleUid);
        return R.ok();
    }

    @ApiOperation(value = "排课时查询社团冲突的活动")
    @PostMapping(value = "/queryConflictClass", produces = "application/json; charset=UTF-8")
    public R<Object> queryConflictClass(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "社团id") @RequestParam(value = "classId") Long classId,
            @ApiParam(value = "活动日期集合") @RequestParam(value = "teachDates") List<String> teachDates,
            @ApiParam(value = "活动开始时间 HH:mm") @RequestParam(value = "beginTime") String beginTime,
            @ApiParam(value = "活动结束时间 HH:mm") @RequestParam(value = "endTime") String endTime
    ) {
        List<CaScheduleLesson> lessonList = scheduleLessonService.queryConflictLessonToClass(corpUid, storeUid, teachDates, beginTime, endTime, classId);

        List<String> lessonUids = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(lessonList)) {
            lessonUids = lessonList.stream().map(CaScheduleLesson::getLessonUid).collect(Collectors.toList());
            return R.fail(4001, "选择的日期时间段内社团活动冲突", lessonUids);
        }
        return R.ok();
    }

    @ApiOperation(value = "获取活动的主讲导读（判断活动冲突）")
    @PostMapping(value = "/getTeachers", produces = "application/json; charset=UTF-8")
    public R<Object> getTeachers(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "活动日期集合") @RequestParam(value = "teachDates") List<String> teachDates,
            @ApiParam(value = "活动开始时间 HH:mm") @RequestParam(value = "beginTime") String beginTime,
            @ApiParam(value = "活动结束时间 HH:mm") @RequestParam(value = "endTime") String endTime,
            @ApiParam(value = "主讲导读uid") @RequestParam(value = "teacherUid", required = false) String teacherUid,
            @ApiParam(value = "课表uid") @RequestParam(value = "scheduleUid", required = false) String scheduleUid,
            @ApiParam(value = "活动uid") @RequestParam(value = "lessonUid", required = false) String lessonUid
    ) {
        List<CorpTeacherDto> list = staffService.getCorpTeachers(storeUid, null, teacherUid, 1);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> usernames = new ArrayList<>();
            for (CorpTeacherDto object : list) {
                String fullName = object.getFullName();
                String nickName = object.getNickName();
                object.setNickName(StringUtils.isNotBlank(nickName) ? nickName : fullName);

                String username = object.getUsername();
                usernames.add(username);
            }

            // 获取冲突的活动
            List<CaScheduleLesson> lessons = scheduleLessonService.queryConflictLessonToTeachers(corpUid, storeUid,
                    teachDates, beginTime, endTime, usernames, scheduleUid, lessonUid);
            Map<String, String> lessonMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(lessons)) {
                for (CaScheduleLesson lesson : lessons) {
                    lessonMap.put(lesson.getLessonUid(), lesson.getUsernames());
                }
            }
            for (CorpTeacherDto object : list) {
                String username = object.getUsername();
                List<String> lessonUids = new ArrayList<>();
                if (lessonMap.size() > 0) {
                    for (Map.Entry<String, String> entry : lessonMap.entrySet()) {
                        String usernameStr = entry.getValue();
                        if (usernameStr.contains("," + username + ",")) {
                            lessonUids.add(entry.getKey());
                        }
                    }
                }
                object.setLessonUids(lessonUids);
            }
        }
        return R.ok(list);
    }

    @ApiOperation(value = "获取排课活动室（判断活动冲突）")
    @PostMapping(value = "/getClassrooms", produces = "application/json; charset=UTF-8")
    public R<Object> getClassrooms(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "活动日期集合") @RequestParam(value = "teachDates") List<String> teachDates,
            @ApiParam(value = "活动开始时间 HH:mm") @RequestParam(value = "beginTime") String beginTime,
            @ApiParam(value = "活动结束时间 HH:mm") @RequestParam(value = "endTime") String endTime,
            @ApiParam(value = "活动室id") @RequestParam(value = "roomId", required = false) Long roomId,
            @ApiParam(value = "课表uid") @RequestParam(value = "scheduleUid", required = false) String scheduleUid,
            @ApiParam(value = "活动uid") @RequestParam(value = "lessonUid", required = false) String lessonUid
    ) {
        List<JSONObject> array = new ArrayList<>();
        // 排课-按指定id置顶排序
        List<CaClassrooms> list = classroomsService.getByStoreUidOrderTopRoomId(storeUid, roomId);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> roomIds = list.stream().map(CaClassrooms::getId).collect(Collectors.toList());

            // 获取冲突的活动
            List<CaScheduleLesson> lessons = scheduleLessonService.queryConflictLessonToRooms(corpUid, storeUid,
                    teachDates, beginTime, endTime, roomIds, scheduleUid, lessonUid);

            Map<Long, Set<String>> lessonMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(lessons)) {
                lessonMap = lessons.stream().collect(Collectors.groupingBy(CaScheduleLesson::getRoomId, Collectors.mapping(CaScheduleLesson::getLessonUid, Collectors.toSet())));
            }
            for (CaClassrooms room : list) {
                JSONObject object = JsonUtil.toJsonObject(room);
                Set<String> lessonUids = new HashSet<>();
                if (null != lessonMap && lessonMap.size() > 0) {
                    lessonUids = lessonMap.get(room.getId());
                }
                object.put("lessonUids", lessonUids);

                array.add(object);
            }
        }
        return R.ok(array);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "创建/编辑活动计划")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "活动计划id") @RequestParam(value = "scheduleUid", required = false) String scheduleUid,
            @ApiParam(value = "活动日期集合") @RequestParam(value = "teachDates") List<String> teachDates,
            @ApiParam(value = "社团id") @RequestParam(value = "classId") Long classId,
            @ApiParam(value = "社团名称") @RequestParam(value = "className") String className,
            @ApiParam(value = "活动开始时间 HH:mm") @RequestParam(value = "beginTime") String beginTime,
            @ApiParam(value = "活动结束时间 HH:mm") @RequestParam(value = "endTime") String endTime,
            @ApiParam(value = "活动室id") @RequestParam(value = "roomId") Long roomId,
            @ApiParam(value = "活动室名称") @RequestParam(value = "roomName") String roomName,
            @ApiParam(value = "导读json {teacherType:0,staffUid:'',username:'',fullName:'',nickName:'',pubPhone:'',priPhone:''}")
            @RequestParam(value = "teacherJson") String teacherJson,
            @ApiParam(value = "活动内容") @RequestParam(value = "content", required = false) String content,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark
    ) throws Exception {
        // 1.选社团和服务项目
        // 2.选择日期
        // 3.选择活动时间 ，判断社团活动冲突
        // 4.选择活动室，判断冲突
        // 5.选择主讲导读，判断冲突
        if (CollectionUtils.isEmpty(teachDates))
            return R.fail("请先选择活动日期");
        if (teachDates.size() > 31)
            return R.fail("活动数量一次不能超过31个");
        if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime))
            return R.fail("没有设置开始或结束时间");
        if (null == roomId)
            return R.fail("没有设置活动室");

        if (StringUtils.isBlank(teacherJson))
            return R.fail("没有添加导读");
        List<CaTeacher> teacherList = JSONArray.parseArray(teacherJson, CaTeacher.class);

        List<String> usernameList = new ArrayList<>();
        // 主讲导读username
        String topTeacherUid = "";
        // 主讲导读名
        String topTeacherName = "";
        for (CaTeacher teacher : teacherList) {
            usernameList.add(teacher.getUsername());
            if (StringUtils.isBlank(teacher.getStaffUid()))
                return R.fail("导读标识传递错误导读：" + teacher.getUsername());

            // 设置主讲导读
            if (teacher.getTeacherType().equals(1)) {
                topTeacherUid = teacher.getUsername();
                topTeacherName = teacher.getFullName();
            }
        }
        if (StringUtils.isBlank(topTeacherUid) || StringUtils.isBlank(topTeacherName))
            return R.fail("没有设置主讲导读");

        CaClassrooms caClassrooms = classroomsService.getBean(storeUid, roomId);
        if (caClassrooms == null)
            return R.fail("未查询到教室");

        CaClass caClass = classService.getById(classId);
        if (null == caClass) return R.fail("社团获取失败");
        if (!caClass.getEnabled().equals(1)) return R.fail("社团已被禁用，不能操作");
        if (!caClass.getCloseStatus().equals(1)) return R.fail("社团已结业，不能操作");
        if (null == caClass.getProjectUid()) return R.fail("社团没有设置服务，不能操作");
        if (null == caClass.getStageUid()) return R.fail("社团没有设置服务阶段，不能操作");

        // 活动表的教师username集合
        String usernames = "," + String.join(",", usernameList) + ",";
        // 获取当前社团的会员数量
        int studentNum = NepUtil.nullToZero(caClass.getStudentNum());

        CaSchedule data = null;
        boolean add = false;
        if (StringUtils.isBlank(scheduleUid)) {
            // 创建
            add = true;

            // 判断门店未进行的活动数量超过上限
            String msg = judgeNotConductedCntByToday(corpUid, storeUid);
            if (StringUtils.isNotBlank(msg))
                return R.fail(msg);

            scheduleUid = KitUtil.getUuid();
            data = new CaSchedule();
            data.setCorpUid(corpUid);
            data.setStoreUid(storeUid);
            data.setStoreName(storeName);
            data.setScheduleUid(scheduleUid);
            data.setFreeStatus(caClass.getFreeStatus());
            data.setStatus(1);
            data.setUseLessonNum(0);
            data.setAddStaffUid(staffUid);
            data.setAddStaffName(staffName);
            data.setClassId(classId);
            data.setClassUid(caClass.getUid());
            data.setClassName(className);
            data.setProjectUid(caClass.getProjectUid());
            data.setProductName(caClass.getProductName());
            data.setStageUid(caClass.getStageUid());
            data.setStageName(caClass.getStageName());
            String days = String.join(",", teachDates);
            data.setTeachDates("," + days + ",");
            data.setBeginTime(beginTime);
            data.setEndTime(endTime);
            data.setLessonNum(teachDates.size());
        } else {
            // 编辑
            data = scheduleService.getSchedule(storeUid, scheduleUid);
            if (null == data)
                return R.fail("活动计划获取失败");
            if (data.getUseLessonNum() > 0)
                return R.fail("活动计划下的活动已开始，不能操作");
        }
        data.setTeacherUid(topTeacherUid);
        data.setTeacherName(topTeacherName);
        data.setUsernames(usernames);
        data.setRoomId(roomId);
        data.setRoomUid(caClassrooms.getUid());
        data.setRoomName(roomName);
        data.setContent(content);
        data.setStudentNum(studentNum);
        data.setRemark(NepUtil.nullToZero(remark));
        data.setLastStaffUid(staffUid);
        data.setLastStaffName(staffName);
        scheduleService.saveOrUpdate(data);

        if (add) {
            // 创建活动表的主讲导读
            ScheduleUtil.newTeachers(teacherList, corpUid, storeUid, scheduleUid, null, staffUid, staffName);
            teacherService.saveOrUpdateBatch(teacherList);

            // 创建活动表的活动
            List<CaScheduleLesson> newList = new ArrayList<>();
            for (String teachDate : teachDates) {
                CaScheduleLesson lesson = ScheduleUtil.newLesson(data, teachDate, studentNum, usernames, topTeacherUid, topTeacherName);
                newList.add(lesson);
            }
            // 保存活动表的活动
            scheduleLessonService.saveOrUpdateBatch(newList);

            // 更新社团的排活动数
            classService.updateScheduleNum(corpUid, storeUid, classId, 1);
        } else {
            // 删除原教师
            teacherService.dropTeacher(storeUid, scheduleUid);
            // 创建活动表的主讲导读
            ScheduleUtil.newTeachers(teacherList, corpUid, storeUid, scheduleUid, null, staffUid, staffName);
            teacherService.saveOrUpdateBatch(teacherList);

            // 更新未开始活动的活动信息
            scheduleLessonService.updateLessons(
                    corpUid, storeUid, scheduleUid, data.getRoomId(), data.getRoomUid(), data.getRoomName(),
                    data.getContent(), usernames, topTeacherUid, topTeacherName, staffUid, staffName, remark
            );
        }
        return R.ok();
    }

    @ApiOperation(value = "快速创建活动日程")
    @PostMapping(value = "/quickCreateLesson", produces = "application/json; charset=UTF-8")
    public R<Object> quickCreateLesson(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "社团名") @RequestParam(value = "className") String className,
            @ApiParam(value = "活动服务uid") @RequestParam(value = "projectUid") String projectUid,
            @ApiParam(value = "活动服务名称") @RequestParam(value = "productName") String productName,
            @ApiParam(value = "服务阶段uid") @RequestParam(value = "stageUid") String stageUid,
            @ApiParam(value = "服务阶段名称") @RequestParam(value = "stageName") String stageName,
            @ApiParam(value = "活动日期") @RequestParam(value = "teachDate") String teachDate,
            @ApiParam(value = "活动开始时间 HH:mm") @RequestParam(value = "beginTime") String beginTime,
            @ApiParam(value = "活动结束时间 HH:mm") @RequestParam(value = "endTime") String endTime,
            @ApiParam(value = "活动室id") @RequestParam(value = "roomId") Long roomId,
            @ApiParam(value = "活动室名称") @RequestParam(value = "roomName") String roomName,
            @ApiParam(value = "导读json {teacherType:0,staffUid:'',username:'',fullName:'',nickName:'',pubPhone:'',priPhone:''}")
            @RequestParam(value = "teacherJson") String teacherJson,
            @ApiParam(value = "活动内容") @RequestParam(value = "content", required = false) String content,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(value = "会员json {memberUid:'',memberName:''}") @RequestParam(value = "memberJson", required = false) String memberJson
    ) throws Exception {
        if (StringUtils.isBlank(projectUid))
            return R.fail("请先选择服务项目");
        if (StringUtils.isBlank(stageUid))
            return R.fail("请先选择服务阶段");
        if (StringUtils.isBlank(className))
            return R.fail("请先填写社团名称");
        if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime))
            return R.fail("没有设置开始或结束时间");
        if (null == roomId)
            return R.fail("没有设置活动室");
        if (StringUtils.isBlank(teacherJson))
            return R.fail("没有设置主讲导读");
        if (StringUtils.isBlank(teacherJson))
            return R.fail("没有添加主讲导读");

        // 判断门店未进行的活动数量超过上限
        String msg = judgeNotConductedCntByToday(corpUid, storeUid);
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        List<CaTeacher> teacherList = JSONArray.parseArray(teacherJson, CaTeacher.class);
        List<String> usernameList = new ArrayList<>();
        // 主讲导读username
        String topTeacherUid = "";
        // 主讲导读名
        String topTeacherName = "";
        for (CaTeacher teacher : teacherList) {
            usernameList.add(teacher.getUsername());
            if (StringUtils.isBlank(teacher.getStaffUid()))
                return R.fail("导读标识传递错误导读：" + teacher.getUsername());

            // 设置主讲导读
            if (teacher.getTeacherType().equals(1)) {
                topTeacherUid = teacher.getUsername();
                topTeacherName = teacher.getFullName();
            }
        }
        if (StringUtils.isBlank(topTeacherUid) || StringUtils.isBlank(topTeacherName))
            return R.fail("没有设置主讲导读");

        // 会员信息
        List<Members> membersList = new ArrayList<>();
        if (StringUtils.isNotBlank(memberJson)) {
            JSONArray memberUids = JSONArray.parseArray(memberJson);
            if (CollectionUtils.isEmpty(memberUids))
                return R.fail("会员信息解析失败");

            Set<String> setMemberUids = new HashSet<>();
            for (int i = 0; i < memberUids.size(); i++) {
                JSONObject jsonObject = memberUids.getJSONObject(i);
                String memberUid = jsonObject.getString("memberUid");
                String memberName = jsonObject.getString("memberName");
                if (StringUtils.isBlank(memberUid))
                    return R.fail("会员标识传递错误会员：" + memberName);
                if (setMemberUids.contains(memberUid))
                    return R.fail("发现会员被重复添加会员：" + memberName);
                setMemberUids.add(memberUid);
            }

            membersList = membersService.getByUids(Lists.newArrayList(setMemberUids));
            if (CollectionUtils.isEmpty(membersList))
                return R.fail("没有查询到会员信息");
        }

        Stores stores = storesService.getByUid(storeUid);
        if (stores == null)
            return R.fail("未查询到门店信息");

        CaClassrooms caClassrooms = classroomsService.getBean(storeUid, roomId);
        if (caClassrooms == null)
            return R.fail("未查询到教室");

        StoreProjects storeProjects = storeProjectsService.getByUid(projectUid);
        if (storeProjects == null)
            return R.fail("服务项目获取失败");
        if (!storeProjects.getEnabled().equals(1))
            return R.fail("服务项目已被禁用");

        // 活动的教师username集合
        String usernames = "," + String.join(",", usernameList) + ",";
        // 获取当前社团的会员数量
        int studentNum = membersList.size();
        String scheduleUid = KitUtil.getUuid();

        // 创建
        CaSchedule data = new CaSchedule();
        data.setScheduleUid(scheduleUid);
        data.setCorpUid(corpUid);
        data.setStoreUid(storeUid);
        data.setStoreName(storeName);
        data.setFreeStatus(storeProjects.getFreeStatus());
        data.setStatus(1);
        data.setAddStaffUid(staffUid);
        data.setAddStaffName(staffName);
        data.setClassId(null);
        data.setClassUid(null);
        data.setClassName(className);
        data.setProjectUid(projectUid);
        data.setProductName(productName);
        data.setStageUid(stageUid);
        data.setStageName(stageName);
        data.setTeachDates("," + teachDate + ",");
        data.setBeginTime(beginTime);
        data.setEndTime(endTime);
        data.setUseLessonNum(0);
        data.setLessonNum(1);
        data.setTeacherUid(topTeacherUid);
        data.setTeacherName(topTeacherName);
        data.setUsernames(usernames);
        data.setRoomId(roomId);
        data.setRoomUid(caClassrooms.getUid());
        data.setRoomName(roomName);
        data.setContent(content);
        data.setStudentNum(studentNum);
        data.setRemark(NepUtil.nullToZero(remark));
        data.setLastStaffUid(staffUid);
        data.setLastStaffName(staffName);
        scheduleService.saveOrUpdate(data);

        // 创建活动表的主讲导读
        ScheduleUtil.newTeachers(teacherList, corpUid, storeUid, scheduleUid, null, staffUid, staffName);
        teacherService.saveOrUpdateBatch(teacherList);

        // 创建活动表的活动
        CaScheduleLesson newLesson = ScheduleUtil.newLesson(data, teachDate, studentNum, usernames, topTeacherUid, topTeacherName);
        scheduleLessonService.saveOrUpdate(newLesson);

        // 创建活动的会员点名记录
        if (CollectionUtils.isNotEmpty(membersList)) {
            List<CaCallNames> callNamesList = new ArrayList<>();
            for (Members members : membersList) {
                CaCallNames callName = ScheduleUtil.newCallName(
                        null, newLesson, corpUid, storeUid, storeName, staffUid, staffName,
                        topTeacherName, members.getId(), members.getUid(), members.getMemberName(), members.getMob(),
                        1, null, null, 0, null, remark
                );
                callNamesList.add(callName);
            }
            callNameService.saveOrUpdateBatch(callNamesList);
        }

        return R.ok();
    }

    /**
     * 判断门店未进行的活动数量超过上限
     */
    private String judgeNotConductedCntByToday(String corpUid, String storeUid) {
        long cnt = scheduleLessonService.getNotConductedCntByToday(corpUid, storeUid, DateUtil.getNowDateStr());
        if (cnt >= 800)
            return "门店未进行的活动总数：" + cnt + "，上限800条";
        return "";
    }

}